package org.quarenden.demo.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.omg.CORBA.PRIVATE_MEMBER;
import org.quarenden.demo.feign.IdGeneratorFeignClient;
import org.quarenden.demo.feign.MicroService1FeignClient;
import org.quarenden.demo.pojo.MicroService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class IdGeneratorController {
    private static final Logger logger = LoggerFactory.getLogger(IdGeneratorController.class);

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private IdGeneratorFeignClient idGeneratorFeignClient;


    /**
     * 非Feign方式调用
     * @param idType
     * @return
     */
    @HystrixCommand(fallbackMethod = "idGeneratorFallBack")
    @GetMapping("/id/{idType}")
    public String idGenerator(@PathVariable String idType){
        ServiceInstance serviceInstance = loadBalancerClient.choose("id-generator");
        logger.info("访问路径:"+"{}:{}:{}",serviceInstance.getServiceId(),serviceInstance.getHost(),serviceInstance.getPort());
        return this.restTemplate.getForObject("http://id-generator/"+idType,String.class);
    }

    public String idGeneratorFallBack(String idType,Throwable throwable){
        logger.error("进入回退方法，异常：",throwable);
        return "-1";
    }

    /**
     * Feign方式调用
     * @param idType
     * @return
     */
    @GetMapping("/id1/{idType}")
    public String idGenerator1(@PathVariable String idType){
        return idGeneratorFeignClient.idGenerator(idType);
    }

}
